<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <link rel="icon" type="image/svg+xml" href="/vite.svg" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>IndexedDB library Demo</title>
        <style>
            #list table {
                width: 1000px;
            }

            #list table td {
                border: 1px solid black;
            }
        </style>
    </head>
    <body>
        <div id="ctrl">
            <div>
                书名: <input type="text" id="input-bookname" /> 类型:
                <select id="input-booktype">
                    <option value="故事书">故事书</option>
                    <option value="科学书">科学书</option>
                    <option value="美术书">美术书</option>
                    <option value="教科书">教科书</option>
                </select>
                <button id="btn-addbook">添加图书</button>
                <button id="btn-clearstore">清除图书库</button>
                <button id="btn-adds">批量添加图书</button>
            </div>
            <div>
                过滤：
                <label
                    ><input
                        type="radio"
                        name="filter"
                        class="input-filter"
                        value="all"
                        checked
                    />
                    全部</label
                >
                <label
                    ><input
                        type="radio"
                        name="filter"
                        class="input-filter"
                        value="故事书"
                    />
                    故事书</label
                >
                <label
                    ><input
                        type="radio"
                        name="filter"
                        class="input-filter"
                        value="科学书"
                    />
                    科学书</label
                >
                <label
                    ><input
                        type="radio"
                        name="filter"
                        class="input-filter"
                        value="美术书"
                    />
                    美术书</label
                >
                <label
                    ><input
                        type="radio"
                        name="filter"
                        class="input-filter"
                        value="教科书"
                    />
                    教科书</label
                >
            </div>
        </div>

        <div id="list">
            <table>
                <thead>
                    <tr>
                        <td>主键</td>
                        <td>数据</td>
                        <td>操作</td>
                    </tr>
                </thead>
                <tbody id="list-body"></tbody>
            </table>
        </div>
        <script type="module">
                        // 这个是开发测试文件
            import IDB from '../dist/index.js'

            let idb = new IDB('demo', 1, {

                onupgradeneeded(evt) {

                    const db = evt.target.result;

                    if (!db.objectStoreNames.contains('book')) {
                        let objectStore = db.createObjectStore('book', { keyPath: 'id', autoIncrement: true });
                        objectStore.createIndex('id', 'id', { unique: true });
                        objectStore.createIndex('name', 'name', { unique: true });
                        objectStore.createIndex('type', 'type', { unique: false });
                    }

                },

                onsuccess(evt) {
                    listBook()
                },

            });


            let tbody = document.getElementById('list-body');
            let inputBookName = document.getElementById('input-bookname');
            let inputBookType = document.getElementById('input-booktype');

            // 添加
            document.getElementById('btn-addbook').addEventListener('click', evt => {
                idb
                    .store('book')
                    .add({
                        name: inputBookName.value,
                        type: inputBookType.value
                    })
                    .then(res => listBook())
                    .catch(err => console.log('addError', err))
            });

            // 批量添加
            document.getElementById('btn-adds').addEventListener('click', evt => {
                idb.store('book').adds([
                    { name: '小老鼠抓小猫的故事', type: '故事书' },
                    { name: '中国人要有信仰', type: '教科书' },
                    { name: '谁是最可恨的人', type: '故事书' },
                    { name: '为什么要天天向上', type: '教科书' },
                    { name: '问我啥都不知道', type: '科学书' },
                    { name: '跟我学画大鸭蛋', type: '美术书' },
                    { name: '体育课上学数学', type: '教科书' },
                ]).then(res => {
                    console.log('adds', res);
                    listBook();
                });
            });


            // 删除、修改
            document.body.addEventListener('click', evt => {

                let target = evt.target;

                // 删除
                if (target.classList.contains('btn-remove')) {
                    idb.store('book').delete(Number(target.dataset.key)).then(res => listBook());
                }

                // 修改
                if (target.classList.contains('btn-update')) {

                    let oldValue = JSON.parse(target.dataset.value);

                    idb.store('book').update({
                        ...oldValue,
                        name: prompt('请输入新书名')
                    }).then(res => listBook());

                }

                // 过滤
                if (target.classList.contains('input-filter')) {
                    listBook();
                }

            });

            // 清除库数据
            document.getElementById('btn-clearstore').addEventListener('click', evt => {
                idb.store('book').clear().then(res => listBook());
            });

            // 列表
            function listBook() {

                let radios = [...document.getElementsByClassName('input-filter')];
                let filterType = (radios.find((el) => el.checked)).value;
                let filter = filterType === 'all' ? undefined : data => data.type === filterType; // 过滤器

                idb.store('book').gets(filter).then(data => {

                    tbody.innerHTML = '';
                    data.forEach(item => {

                        let node = document.createElement('tr');
                        node.innerHTML = `
                            <tr>
                                <td>${item.id}</td>
                                <td>${JSON.stringify(item)}</td>
                                <td>
                                    <button class="btn-remove" data-key="${item.id}">删除</button>
                                    <button class="btn-update" data-key="${item.id}" data-value='${JSON.stringify(item)}'>修改</button>
                                </td>
                            </tr>
                        `;

                        tbody.append(node);

                    });
                });
            }
        </script>
    </body>
</html>
